# -*- coding: utf-8 -*-
import json
import uuid
import os
import sys

basic_path = sys.path[0]
os.system('')
 
# 升级包版本号
def UpgradePackageVersion():
  print("\033[1;32;40m{}\033[0m".format("开始升级包版本号"))
  
  mod_package = { }

  upgrade = [0,0,1]

  for dirpath, dirnames, filenames in os.walk(basic_path):  
    dirpath_list =  dirpath.split("\\")
    if len (dirpath_list)>5 and dirpath_list[-4] == "mods":
      package_name = dirpath_list[-3]
      mod_package.setdefault(package_name,{
        "behavior_packs": [ ],
        "resource_packs": [ ],
        "world_packs" : ""
      })
      if dirpath_list[-2] in ("behavior_packs", "resource_packs"):
        # print (dirpath)

        manifest = "\\".join((dirpath, "manifest.json"))
        pack_manifest = "\\".join((dirpath, "pack_manifest.json"))
        # print ("acme_log_", os.path.exists(manifest), os.path.exists(pack_manifest))
        if os.path.exists(pack_manifest):
          if os.path.exists(manifest):
            os.remove(manifest)
            print("\033[1;31;40m{}\033[0m".format("删除多余的 manifest.json 文件"))

          manifest = pack_manifest
        jsondata = {}
        with open(manifest, mode='r', encoding="UTF-8") as file:
          jsondata = json.loads( file.read())
        # jsondata["header"]["version"][2] += 1

        tidaizifuc = "acme~^_^~wuwei"  # 替代占位字符串

        for i,v in enumerate(jsondata["header"]["version"]):
            jsondata["header"]["version"][i] += upgrade[i]

        mod_package[package_name][dirpath_list[-2]].append({
            "pack_id": jsondata["header"]["uuid"],
            "type": "Addon",
            "version":  jsondata["header"]["version"],
          })

        jsondata["header"]["version"] = "{}{}{}".format(tidaizifuc, str( jsondata["header"]["version"]), tidaizifuc)
        for modules in jsondata["modules"]:
          for i,v in enumerate(modules["version"]):
            modules["version"][i] += upgrade[i]
          modules["version"] = "{}{}{}".format(tidaizifuc, str(modules["version"]), tidaizifuc)

      if dirpath_list[-2] == "worlds":
        print (dirpath)
        mod_package[package_name]["world_packs"] = dirpath
  
      with open(manifest, mode='w', encoding="UTF-8") as file:
        jsonstr = json.dumps(jsondata , indent=4, ensure_ascii=False)
        jsonstr = jsonstr.replace('"{}'.format(tidaizifuc), '').replace('{}"'.format(tidaizifuc), '')
        file.write(jsonstr)

  print("\033[1;32;40m{}\033[0m".format("写入加载配置文件"))
  
  for mod in mod_package:
    print (mod)
    behavior_packs = mod_package[mod]["behavior_packs"]
    resource_packs = mod_package[mod]["resource_packs"]
    world_packs_path = mod_package[mod]["world_packs"]
    world_behavior_packs = "\\".join((world_packs_path, "world_behavior_packs.json"))
    with open(world_behavior_packs, mode='w', encoding="UTF-8") as file:
      file.write('[\n  {}\n]'.format(",\n  ".join(json.dumps(x) for x in behavior_packs)) )
    world_resource_packs = "\\".join((world_packs_path, "world_resource_packs.json"))
    with open(world_resource_packs, mode='w', encoding="UTF-8") as file:
      file.write('[\n  {}\n]'.format(",\n  ".join(json.dumps(x) for x in resource_packs)) )

  print("\033[1;32;40m{}\033[0m".format("升级包版本号结束"))


if __name__ == '__main__':
  UpgradePackageVersion()